#include "ProtoText.h"
#include "../net/NetMsg.h"
#include "../lua/LuaRegister.h"

NetMsg* ProtoText::pack_protocol(lua_State* lua, int index)
{
	if (!lua_isstring(lua, index) || !lua_isstring(lua, index + 1)) {
		return nullptr;
	}
	std::string name = lua_tostring(lua, index);
	size_t len = 0;
	const char* result = lua_tolstring(lua, index + 1, &len);
	return new NetMsg(MSG_TYPE_BIN, name, result, len);
}

int ProtoText::unpack_protocol(lua_State* lua, NetMsg* msg)
{
	if (!msg) {
		return 0;
	}
	msg->readHead();
	if (!msg->isVaild()) {
		return 0;
	}
	td_proto::Values raw = td_proto::decode_str_raw(*msg, td_proto::TYPE_RAW);
	if (raw.sub_type != td_proto::TYPE_RAW) {
		return 0;
	}
	lua_pushstring(lua, msg->packName.c_str());
	LuaRegister::pushValues(lua, raw);
	return 2;
}
